﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Xml;
using WebFlipScreenSaver.Model;

namespace WebFlipScreenSaver
{
	public class FlipperSettings
	{

		public static SettingsViewModel LoadSettings(string filename = "WebFlipScreenSaverSettings.xml")
		{
			try
			{
				filename = GetRequiredFullPath(filename);
				if (File.Exists(filename))
				{
					var serializer =
						new System.Runtime.Serialization.DataContractSerializer(typeof(SettingsViewModel));
					using (var reader = XmlReader.Create(filename))
					{
						return serializer.ReadObject(reader) as SettingsViewModel;
					}
				}
				return new SettingsViewModel();
			}
			catch (Exception ex)
			{
				MessageBox.Show(string.Format("Error loading settings from {0}\n\n{1}", filename, ex.ToString()));
				throw;
			}


		}

		public static void SaveSettings<TObject>(TObject data, string filename = "WebFlipScreenSaverSettings.xml")
		{
			try
			{
				filename = GetRequiredFullPath(filename);
				var serializer =
					new System.Runtime.Serialization.DataContractSerializer(typeof(TObject));
				var settings = new XmlWriterSettings();
				settings.Indent = true;
				settings.IndentChars = "\t";

				using (var writer = XmlWriter.Create(filename, settings))
				{
					serializer.WriteObject(writer, data);
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(string.Format("Error saving settings to {0}\n\n{1}", filename, ex.ToString()));
				throw;
			}

		}

		private static string GetRequiredFullPath(string filename)
		{
			var requiredDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify), "WebFlipScreenSaver");
			if(!Directory.Exists(requiredDir))
			{
				Directory.CreateDirectory(requiredDir);
			}
			//var requiredDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			var requestedDir = Path.GetDirectoryName(filename);
			if(requestedDir == null)
			{
				throw new Exception(string.Format("Invalid path: {0}", filename));
			}

			if (requiredDir == null)
			{
				throw new Exception(string.Format("Invalid path: {0}", Assembly.GetExecutingAssembly().CodeBase));
			}
			if (requestedDir.ToLowerInvariant() != requiredDir.ToLowerInvariant())
			{
				filename = Path.Combine(requiredDir, Path.GetFileName(filename));
			}

			return filename;
		}

	}
}
